/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PastResults.java
 *
 * Created on Aug 18, 2009, 7:34:22 AM
 */

package matpred;

import bdl.MatchBean;
import bdl.UtilityBean;
import entities.Match;
import entities.Prediction;
import java.awt.Point;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import utilities.entities.Result;
import utilities.Store;

/**
 *
 * @author Demola
 */
public class PastResults extends javax.swing.JPanel {

    /** Creates new form PastResults */
    public PastResults() {
        initComponents();
        dtm = new DefaultTableModel(){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        mtm = new DefaultTableModel(){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        jTable1.setModel(dtm);
        jTable2.setModel(mtm);
        setTable();
        loadMatches();
    }

    public static PastResults getPastResult(){
        if(pr == null)
            pr = new PastResults();
        return pr;
    }

    private void setTable(){
        dtm.addColumn("S/N");
        dtm.addColumn("Reference Number");
        dtm.addColumn("Predicted Match");
        dtm.addColumn("Date");
        dtm.addColumn("Fixture");
        dtm.addColumn("Predicted Scores");
        dtm.addColumn("Actual Score");
        dtm.addColumn("Rating 1");
        dtm.addColumn("Rating 2");
        dtm.addColumn("-");

        jTable1.getColumnModel().getColumn(9).setMinWidth(0);
        jTable1.getColumnModel().getColumn(9).setMaxWidth(0);
        jTable1.getColumnModel().getColumn(9).setPreferredWidth(0);

        for(int i = 0; i < dtm.getColumnCount(); i++){
            jTable1.getColumnModel().getColumn(i).setResizable(false);
        }

        mtm.addColumn("S/N");
        mtm.addColumn("Predicted Match");
        mtm.addColumn("Date");
        mtm.addColumn("Fixture");
        mtm.addColumn("Scores");
    }

    private void fillTable(Match m){
        predList = (m == null) ? UtilityBean.getPredictions() : UtilityBean.getPredictions(m);
        if(predList != null && !predList.isEmpty()){
//            dtm.setRowCount(0);
            int i = 0;
            for(Prediction p : predList){
                if(p.getId() == 1000 || !Store.exists(p.getFileName())) continue;
                String date = sdf.format(p.getMatch().getMatchDate());
                String rating1 = (p.getRating1() < 0) ? "N/A" : p.getRating1().toString();
                String rating2 = (p.getRating2() < 0) ? "N/A" : p.getRating2().toString();
                dtm.addRow(new Object[]{++i, p.getId(), p.getMatch(), date, p.getMatch().getFixture(),
                p.getPredictedScore(), p.getActualScore(), rating1, rating2, p});
            }
        }
    }

    private void loadMatches(){
        List<Match> pm = UtilityBean.getPMatches();
        if(pm != null && !pm.isEmpty()){
            mtm.setRowCount(0);
            int i = 0;
            for(Match m : pm){
                String date = sdf.format(m.getMatchDate());
                String score = (m.getHomeScore() < 0) ? "N/A" : m.getScores();
                mtm.addRow(new Object[]{++i, m, date, m.getFixture(), score});
            }
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jSeparator1 = new javax.swing.JSeparator();
        jButton5 = new javax.swing.JButton();

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("View Prediction Result");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        jButton2.setText("Delete");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        jButton3.setText("Show Result");
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton3MouseClicked(evt);
            }
        });

        jButton4.setText("Add Scores");
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton4MouseClicked(evt);
            }
        });

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jTable2);

        jButton5.setText("Show All Result");
        jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton5MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 823, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 823, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 542, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE))
                        .addGap(150, 150, 150))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addContainerGap(627, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(12, 12, 12)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4)
                        .addGap(126, 126, 126))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(15, 15, 15)))
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        Point point = evt.getPoint();
        int row = jTable1.rowAtPoint(point);
        int col = jTable1.columnAtPoint(point);
        System.out.println("row: " + row + " col: " + col);
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
         int [] sel = jTable1.getSelectedRows();
         if(sel.length == 0){
             JOptionPane.showMessageDialog(null, "Please select the result you want to view");
         }else{
             ArrayList<Result> result = new ArrayList();
             for(int row : sel){
                 Prediction p = (Prediction) dtm.getValueAt(row, 9);
                 Result r = Store.retrieve(p.getFileName());
                 if(r != null) result.add(r);
             }
             new ResultDialog(result).setVisible(true);
         }
    }//GEN-LAST:event_jButton1MouseClicked

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        dtm.setRowCount(0);
        loadMatches();
    }//GEN-LAST:event_formComponentShown

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
         int [] sel = jTable1.getSelectedRows();
         if(sel.length == 0){
             JOptionPane.showMessageDialog(null, "Please select the result you want to delete");
         }else{
             for(int row : sel){
                 Prediction p = (Prediction) dtm.getValueAt(row, 9);
                 if(Store.delete(p.getFileName())){
                     UtilityBean.deletePrediction(p);
                 }else{
                     JOptionPane.showMessageDialog(null, "result cannot be deleted");
                 }

             }
         }
    }//GEN-LAST:event_jButton2MouseClicked

    private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked
         dtm.setRowCount(0);
         int [] sel = jTable2.getSelectedRows();
         if(sel.length == 0){

         }else{
             for(int i = 0; i < sel.length; i++){
                 Match m = (Match) mtm.getValueAt(i, 1);
                 fillTable(m);
             }
         }
    }//GEN-LAST:event_jButton3MouseClicked

    private void jButton5MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseClicked
        dtm.setRowCount(0);
        fillTable(null);
    }//GEN-LAST:event_jButton5MouseClicked

    private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked
         //check if score exist
        int sel = jTable2.getSelectedRow();
        if(sel == -1) return;
        if(!mtm.getValueAt(sel, 4).toString().contains("N/A")){
            JOptionPane.showMessageDialog(null, "Score already exist for the selected match");
            return;
        }
        Match match = (Match) mtm.getValueAt(sel, 1);
        String hs = JOptionPane.showInputDialog("Enter score for " + match.getHome().getName());
        String as = JOptionPane.showInputDialog("Enter score for " + match.getAway().getName());
        try{
            int homeScore = Integer.parseInt(hs);
            int awayScore = Integer.parseInt(as);
            match.setHomeScore(homeScore);
            match.setAwayScore(awayScore);
            match = MatchBean.updateMatch(match);
            System.out.println(match.getScores());
        }catch(Exception ex){
            System.out.println(ex.getMessage());
        }
        List<Prediction> plist = UtilityBean.getPredictions(match);
        for(Prediction p : plist){
            p.setActualScore(match.getScores());
            int rating1 = (p.getPredictedScore().equals(match.getScores())) ? 1 : 0;
            int rating2 = (match.getHomeScore() == match.getAwayScore()) ? 1 : 0;
            p.setRating1(rating1);
            p.setRating2(rating2);
            UtilityBean.updatePrediction(p);
        }
        formComponentShown(null);
    }//GEN-LAST:event_jButton4MouseClicked


    private static SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy");
    private static PastResults pr;

    private DefaultTableModel mtm;
    private List<Prediction> predList;
    private DefaultTableModel dtm;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables


    
}
